package com.service.core;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.service.utils.ExecuteCommand;
import com.service.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class HandleService {

    @Value("${vh.url:http://localhost:8210/api}")
    private String vhUrl;

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void Handle() {
        log.info("执行定时任务 start");
        String response = HttpClientUtil.doGet(vhUrl + "/system/user/profile/getInternet");
        log.info("response: {}", JSONObject.toJSONString(response));
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") == 200) {
            JSONArray arrays = jsonObject.getJSONArray("data");
            for (Object array : arrays) {
                try {
                    JSONObject idJson = new JSONObject();
                    JSONObject obj = (JSONObject) array;
                    Integer isOpen = obj.getInteger("isOpen");
                    if (isOpen == 1) {
                        ExecuteCommand.handleExecute("sudo systemctl start nginx");
                    }else if (isOpen == 2) {
                        ExecuteCommand.handleExecute("sudo systemctl stop nginx");
                    }
                    idJson.put("id", obj.getLong("id"));
                    // 执行命令
                    HttpClientUtil.doPostJson(vhUrl + "/system/user/profile/updateInternet",idJson.toJSONString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        log.info("执行定时任务 end");
    }
}
